/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.controllers;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpSession;
import org.domain.Item;
import org.helper.RequestCatalog;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 *
 * @author Shaun McCready
 */
public class LoginHandler extends HttpServlet {


     private static final String USERS = "users.xml";

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

        String inputname = request.getParameter("username");
        String inputpword = request.getParameter("pword");

        DocumentBuilderFactory docBuilderFactory = null;
        DocumentBuilder docBuilder = null;
        Document doc = null;

        try
        {

          docBuilderFactory = DocumentBuilderFactory.newInstance();
          docBuilder = docBuilderFactory.newDocumentBuilder();
          doc = docBuilder.parse (new File(LoginHandler.class.getResource(USERS).toURI()));


        } catch (URISyntaxException ex) {
            Logger.getLogger(LoginHandler.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(LoginHandler.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(LoginHandler.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(LoginHandler.class.getName()).log(Level.SEVERE, null, ex);
        }



        NodeList allProducts = doc.getElementsByTagName("*");
        doc.getDocumentElement().normalize();

        boolean access = false;

        for (int i = 0; i < allProducts.getLength(); i++) {
            Node node = allProducts.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element) node;

                if (element.getAttribute("user-name").equalsIgnoreCase(inputname))
                {
                    System.out.println("User name works.....");
                    if (element.getAttribute("password").equalsIgnoreCase(inputpword))
                        {
                        System.out.println("Password works.....");


                        //client has successfully logged into the system
                        access = true;

                        HttpSession session = request.getSession();
                        session.setAttribute("user", inputname);

                        //setting a timeout of 20 minutes
                        session.setMaxInactiveInterval(1200);
                        
                        //set the inventory
                        RequestCatalog rc = new RequestCatalog();
                        ArrayList<Item> list = new ArrayList<Item>();
                        list = rc.getItems();
                        session.setAttribute("inventory", list);

                        int cart = 0;
                        session.setAttribute("cart", cart);
                        //System.out.println("ID :" + list.get(0).getItemId() + ", Man:" +list.get(0).getManufacturer()+ ", Prod:" + list.get(0).getProduct());
                        //System.out.println("ID :" + list.get(1).getItemId() + ", Man:" +list.get(1).getManufacturer()+ ", Prod:" + list.get(1).getProduct());



                        }
                }
            }
        }

        if (access == true)
        {
            request.getRequestDispatcher("home.jsp").forward(request, response);
        }
        else if (access == false)
        {
            String error = "Username or Password is incorrect";
            request.setAttribute("ERROR", error);
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
        else
        {
            System.out.println("Error in the loginhandler servlet");
        }



    } 



    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);


    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
